﻿using FileTransferSystem.Models;
using FileTransferSystem.Utilities;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace FileTransferSystem.Services
{
    /// <summary>
    /// 文件传输管理器，协调发送和接收操作
    /// </summary>
    public class FileTransferManager
    {
        private readonly HistoryManager _historyManager;
        private readonly string _tempFolderPath;
        private readonly List<FileTransfer> _activeTransfers;

        public FileTransferManager(HistoryManager historyManager)
        {
            _historyManager = historyManager;

            // 创建临时文件夹用于存储未完成的传输
            string appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            _tempFolderPath = Path.Combine(appDataPath, "FileTransferSystem", "Temp");

            if (!Directory.Exists(_tempFolderPath))
            {
                Directory.CreateDirectory(_tempFolderPath);
            }

            _activeTransfers = new List<FileTransfer>();
        }

        /// <summary>
        /// 检查是否有未完成的传输
        /// </summary>
        public async Task CheckUnfinishedTransfers()
        {
            var tempFiles = Directory.GetFiles(_tempFolderPath, "*.json");

            if (tempFiles.Length == 0)
                return;

            Console.WriteLine($"发现 {tempFiles.Length} 个未完成的传输");
            Console.WriteLine("是否要继续这些传输? (y/n) - 输入0返回主菜单");

            var response = Console.ReadLine()?.ToLower();
            if (response == "0") return;
            if (response != "y")
                return;

            foreach (var tempFile in tempFiles)
            {
                try
                {
                    var json = File.ReadAllText(tempFile);
                    var transferInfo = JsonSerializer.Deserialize<FileTransferInfo>(json);

                    if (transferInfo != null)
                    {
                        Console.WriteLine($"发现未完成的传输: {transferInfo.FileName}");
                        Console.WriteLine($"已传输: {transferInfo.TransferredBytes} / {transferInfo.FileSize} 字节");
                        Console.WriteLine("是否继续? (y/n) - 输入0返回主菜单");

                        var continueResponse = Console.ReadLine()?.ToLower();
                        if (continueResponse == "0") return;
                        if (continueResponse == "y")
                        {
                            if (transferInfo.IsSender)
                            {
                                await StartTransfer(transferInfo, true);
                            }
                            else
                            {
                                await StartReceivingTransfer(transferInfo, true);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"加载未完成传输失败: {ex.Message}");
                }
            }
        }

        /// <summary>
        /// 开始发送文件
        /// </summary>
        public async Task StartSending()
        {
            Console.WriteLine($"请输入接收端IP地址 (默认: {_historyManager.DefaultIp}) - 输入0返回主菜单:");
            var ipInput = Console.ReadLine();
            if (ipInput == "0") return;
            var ipAddress = string.IsNullOrEmpty(ipInput) ? _historyManager.DefaultIp : ipInput;

            Console.WriteLine($"请输入接收端端口号 (默认: {_historyManager.DefaultPort}) - 输入0返回主菜单:");
            var portInput = Console.ReadLine();
            if (portInput == "0") return;
            var port = string.IsNullOrEmpty(portInput) ? _historyManager.DefaultPort : int.Parse(portInput);

            // 测试连接
            if (!await TestConnection(ipAddress, port))
            {
                Console.WriteLine("无法连接到接收端，请检查IP和端口是否正确，以及接收端是否已启动");
                return;
            }

            Console.WriteLine("请输入要发送的文件路径 - 输入0返回主菜单:");
            var filePath = Console.ReadLine();
            if (filePath == "0") return;

            // 清理路径
            filePath = PathHelper.CleanPath(filePath);

            if (!File.Exists(filePath))
            {
                Console.WriteLine("文件不存在或路径不合法");
                return;
            }

            var fileInfo = new FileInfo(filePath);
            var transferInfo = new FileTransferInfo
            {
                FilePath = filePath,
                FileName = fileInfo.Name,
                FileSize = fileInfo.Length,
                IpAddress = ipAddress,
                Port = port,
                IsSender = true,
                TempFilePath = Path.Combine(_tempFolderPath, $"send_{Guid.NewGuid()}.tmp")
            };

            await StartTransfer(transferInfo, false);
        }

        /// <summary>
        /// 测试与接收端的连接
        /// </summary>
        private async Task<bool> TestConnection(string ipAddress, int port)
        {
            try
            {
                Console.WriteLine("正在测试连接...");

                // 使用简单的TCP连接测试
                using var client = new System.Net.Sockets.TcpClient();
                var task = client.ConnectAsync(ipAddress, port);
                var timeoutTask = Task.Delay(3000); // 3秒超时

                var completedTask = await Task.WhenAny(task, timeoutTask);

                if (completedTask == timeoutTask)
                {
                    Console.WriteLine("连接超时");
                    return false; // 连接超时
                }

                // 发送测试消息
                var stream = client.GetStream();
                var testMessage = Encoding.UTF8.GetBytes("TEST_CONNECTION");
                await stream.WriteAsync(testMessage, 0, testMessage.Length);

                // 等待响应
                var responseBuffer = new byte[1024];
                var responseTask = stream.ReadAsync(responseBuffer, 0, responseBuffer.Length);
                var responseTimeout = Task.Delay(1000); // 1秒超时

                var responseCompleted = await Task.WhenAny(responseTask, responseTimeout);

                if (responseCompleted == responseTimeout)
                {
                    Console.WriteLine("测试响应超时");
                    return false;
                }

                var response = Encoding.UTF8.GetString(responseBuffer, 0, responseTask.Result);
                if (response == "TEST_RESPONSE")
                {
                    Console.WriteLine("连接测试成功");
                    return true;
                }

                Console.WriteLine("测试响应无效");
                return false;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"连接测试失败: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 开始接收文件
        /// </summary>
        public async Task StartReceiving()
        {
            // 获取可用端口列表
            var availablePorts = PortScanner.FindAvailablePortsList();

            if (availablePorts.Count == 0)
            {
                Console.WriteLine("没有找到可用端口，请检查网络配置");
                return;
            }

            // 显示可用端口
            Console.WriteLine("可用端口列表:");
            for (int i = 0; i < availablePorts.Count; i++)
            {
                Console.WriteLine($"{i + 1}. {availablePorts[i]}");
            }

            // 默认选择上次使用的端口或第一个可用端口
            int defaultPort = _historyManager.DefaultPort;
            if (!availablePorts.Contains(defaultPort))
            {
                defaultPort = availablePorts[0];
            }

            Console.WriteLine($"请输入监听端口号 (默认: {defaultPort}) - 输入0返回主菜单:");
            var portInput = Console.ReadLine();
            if (portInput == "0") return;
            var port = string.IsNullOrEmpty(portInput) ? defaultPort : int.Parse(portInput);

            // 检查端口是否可用
            if (!PortScanner.IsPortAvailable(port))
            {
                Console.WriteLine($"端口 {port} 已被占用，请选择其他端口");
                return;
            }

            // 使用上次的接收文件夹作为默认值
            Console.WriteLine($"请输入保存文件的文件夹路径 (默认: {_historyManager.DefaultReceiveFolder}) - 输入0返回主菜单:");
            var folderPath = Console.ReadLine();
            if (folderPath == "0") return;

            // 如果没有输入路径，使用上次的接收文件夹
            if (string.IsNullOrEmpty(folderPath))
            {
                folderPath = _historyManager.DefaultReceiveFolder;
                Console.WriteLine($"使用上次的接收文件夹: {folderPath}");
            }

            // 清理路径
            folderPath = PathHelper.CleanPath(folderPath);

            // 检查文件夹是否存在
            if (!Directory.Exists(folderPath))
            {
                Console.WriteLine("文件夹不存在，是否创建? (y/n) - 输入0返回主菜单");
                var response = Console.ReadLine()?.ToLower();
                if (response == "0") return;

                if (response == "y")
                {
                    Directory.CreateDirectory(folderPath);
                }
                else
                {
                    Console.WriteLine("操作取消");
                    return;
                }
            }

            var transferInfo = new FileTransferInfo
            {
                Port = port,
                SaveDirectory = folderPath,
                IsSender = false,
                TempFilePath = Path.Combine(_tempFolderPath, $"receive_{Guid.NewGuid()}.tmp")
            };

            await StartReceivingTransfer(transferInfo, false);
        }

        /// <summary>
        /// 开始发送传输
        /// </summary>
        private async Task StartTransfer(FileTransferInfo transferInfo, bool isResume)
        {
            var transfer = new FileTransfer(transferInfo, _historyManager, _tempFolderPath);
            _activeTransfers.Add(transfer);

            // 注册取消事件
            transfer.TransferCanceled += OnTransferCanceled;
            transfer.TransferCompleted += OnTransferCompleted;

            await transfer.StartSending(isResume);
        }

        /// <summary>
        /// 开始接收传输
        /// </summary>
        private async Task StartReceivingTransfer(FileTransferInfo transferInfo, bool isResume)
        {
            var transfer = new FileTransfer(transferInfo, _historyManager, _tempFolderPath);
            _activeTransfers.Add(transfer);

            // 注册取消事件
            transfer.TransferCanceled += OnTransferCanceled;
            transfer.TransferCompleted += OnTransferCompleted;

            await transfer.StartReceiving(isResume);
        }

        /// <summary>
        /// 传输取消事件处理
        /// </summary>
        private void OnTransferCanceled(object sender, FileTransferInfo e)
        {
            Console.WriteLine($"传输取消: {e.FileName}");
            _activeTransfers.Remove(sender as FileTransfer);
        }

        /// <summary>
        /// 传输完成事件处理
        /// </summary>
        private void OnTransferCompleted(object sender, FileTransferInfo e)
        {
            Console.WriteLine($"传输完成: {e.FileName}");
            _activeTransfers.Remove(sender as FileTransfer);

            // 添加到历史记录
            if (e.IsSender)
            {
                _historyManager.AddHistory(e.IpAddress, e.Port, e.FilePath, true);
            }
            else
            {
                _historyManager.AddHistory("", e.Port, e.FilePath, false);
            }
        }
    }
}